package com.zhenyi.jiahua.interceptor;

import com.cjw.model.DBMap;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jiahua.common.model.JhStaff;
import com.utils.AuthUtils;
import com.utils.HttpUtils;

public class AuthInterceptor implements Interceptor {

	private void renderLogin(Controller controller) {
		// String before = controller.getRequest().getRequestURI();
		String before = getRequestUrl(controller);
		// controller.redirect("/jh/auth?state=" + URLUtil.encode(before));
		controller.redirect("/jh/auth");
	}

	private String getRequestUrl(Controller controller) {
		String url = controller.getRequest().getRequestURL().toString();
		String queryurl = controller.getRequest().getQueryString();
		if (StrKit.notBlank(queryurl)) {
			url = url + "?" + queryurl;
		}
		return url;
	}

	@Override
	public void intercept(Invocation inv) {

		Controller controller = inv.getController();
		try {
			String uid = AuthUtils.getTokenUid(controller);
			String osm = HttpUtils.getOS(controller.getRequest());
			String cookieOsm = controller.getCookie("osm");
			if (StrKit.isBlank(cookieOsm)) {
				renderLogin(controller);
				return;
			}
			if (cookieOsm.equals(osm)) {
				renderLogin(controller);
				return;
			}
			if (StrKit.notBlank(uid)) {
				try {
					JhStaff staff = JhStaff.dao.findById(Long.valueOf(AuthUtils.getTokenUid(controller)));
					if (staff == null) {
						renderLogin(controller);
						return;
					}
					controller.setAttr("account", staff);
					inv.invoke();
				} catch (Exception e) {
					LogKit.warn("system error", e);
					// renderLogin(controller);
					controller.renderError(500);
					return;
				}
			} else {
				renderLogin(controller);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			DBMap map = new DBMap();
			map.put("status", 500);
			map.put("msg", "出错");
			controller.renderJson(map);
		}
	}

}
